package com.css.dzj.dzjap.modules.info.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.construnit.entity.ConstructionUnitEntity;
import com.css.dzj.dzjap.modules.construnit.entity.QConstructionUnitEntity;
import com.css.dzj.dzjap.modules.enterprise.service.EnterpriseJSService;
import com.css.dzj.dzjap.modules.enterprise.service.EnterpriseService;
import com.css.dzj.dzjap.modules.info.mapper.ConstrMapper;
import com.css.dzj.dzjap.modules.info.service.ConstrService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public  class ConstrServiceImpl implements ConstrService {
    @Autowired
    ConstrMapper constrMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    EnterpriseService enterpriseService;

    @Autowired
    EnterpriseJSService enterpriseJSService;
    @Override
    public QueryResults<ConstructionUnitEntity> getPage(Pageable pageable, String entName, String uniScid, String startTime, String endTime, String createPerson, HttpServletRequest request) {
        //List idNum=enterpriseJSService.idJsHbNumber();
        QConstructionUnitEntity q=QConstructionUnitEntity.constructionUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (entName == null || entName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.entName.like("%" + entName + "%"));
        predicate = (uniScid == null || uniScid.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + uniScid + "%"));
        predicate=(createPerson==null || createPerson.isEmpty())? predicate : ExpressionUtils.and(predicate,q.createPerson.like("%"+createPerson+"%"));
        predicate=ExpressionUtils.and(predicate,q.delFlag.eq(Constant.NO_DELETE));
        if((StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(endTime + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.establishTime.loe(endDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(StringUtils.isEmpty(endTime))){
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.establishTime.goe(startDate));
        }
        if((!StringUtils.isEmpty(startTime))&&(!StringUtils.isEmpty(endTime))){
            Date startDate = null;
            Date endDate=null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(startTime+" "+"00:00:00.000");
                endDate = sf.parse(endTime+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate =ExpressionUtils.and(predicate, q.establishTime.between(startDate,endDate));
        }
        String orgName= ServiceUtil.getOrgName(request);
        if(orgName.contains("建设单位")) {
            String unsid =findUnitCode(ServiceUtil.getLoginName(request));
            if (!StringUtils.isEmpty(unsid)) {
                predicate = ExpressionUtils.and(predicate, q.uniscid.eq(unsid));
            }
        }
        return jpaQueryFactory.selectFrom(q).where(predicate/*,q.uniscid.notIn(idNum)*/).orderBy(q.createTime.desc()).offset(pageable.getOffset()).limit(pageable.getPageSize()).fetchResults();
    }

    @Override
    @Transactional
    public boolean delConstr(String id) {
        constrMapper.deleteById(id);
        return true;
    }

    @Override
    @Transactional
    public void update(ConstructionUnitEntity constructionUnitEntity) {

    }

    @Override
    @Transactional
    public ConstructionUnitEntity findById(String id) {
       ConstructionUnitEntity constructionUnitEntity= constrMapper.findById(id).get();
       if(StringUtils.isEmpty(constructionUnitEntity)){
           return null;
       }
        return constructionUnitEntity;
    }

    @Override
    public QueryResults<ConstructionUnitEntity> getPageConstr(Pageable pageable, String enterpriseName,
                                                              String enterpriseIdNumber) {
        List idNum=enterpriseJSService.idJsHbNumber();
        QConstructionUnitEntity q=QConstructionUnitEntity.constructionUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (enterpriseName == null || enterpriseName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.entName.like("%" + enterpriseName + "%"));
        predicate = (enterpriseIdNumber == null || enterpriseIdNumber.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + enterpriseIdNumber + "%"));
        return jpaQueryFactory.selectFrom(q).where(predicate,q.uniscid.notIn(idNum)).orderBy(q.createTime.desc()).offset(pageable.getOffset()).limit(pageable.getPageSize()).fetchResults();
    }

    @Override
    public String findUnitCode(String userName) {
        QConstructionUnitEntity q=QConstructionUnitEntity.constructionUnitEntity;
        return jpaQueryFactory.select(q.uniscid).from(q).where(q.userName.eq(userName), q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
    }

    @Override
    public HashMap getCount() {
        QConstructionUnitEntity q=QConstructionUnitEntity.constructionUnitEntity;
        List<ConstructionUnitEntity> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        List idNum=enterpriseJSService.idJsNumber();
        HashMap map=new HashMap();
        for (ConstructionUnitEntity contr:list) {
            String address=contr.getLocation();
            String[] arr=address.split("-");
            Long count=jpaQueryFactory.select(q.location.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.location.eq(address),q.id.eq(contr.getId()),q.uniscid.in(idNum)).fetchOne();
            Long value=(Long)map.get(arr[0]);
            if(value==null) {
                if(count!=0) {
                    map.put(arr[0], count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(arr[0],value);
            }
        }
        return map;
    }

    @Override
    public HashMap getCountByYear(String year) {
        QConstructionUnitEntity q=QConstructionUnitEntity.constructionUnitEntity;
        Predicate predicate=q.isNotNull().or(q.isNull());
        List<ConstructionUnitEntity> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        List idNum=enterpriseJSService.idJsNumber();
        HashMap map=new HashMap();
        for (ConstructionUnitEntity contr:list) {
            String address=contr.getLocation();
            String[] arr=address.split("-");
            String arry=null;
            if(arr[0].contains("市")){
                arry=arr[0].replace("市","");
            }else if(arr[0].contains("省")){
                arry=arr[0].replace("省","");
            }
            ComparableExpressionBase<?> creatYear = q.createTime.year();
            predicate =ExpressionUtils.and(predicate,((NumberExpression) creatYear).stringValue().eq(year)) ;
            Long count=jpaQueryFactory.select(q.location.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.location.eq(address),q.id.eq(contr.getId()),q.uniscid.in(idNum),predicate).fetchOne();
            Long value=(Long)map.get(arry);
            if(value==null) {
                if(count!=0) {
                    map.put(arry, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(arry,value);
            }
        }
        return map;
    }

   /* @Override
    public List<ConstructionUnitEntity> getPageLH(String unitName, String uniscid) {
        //建设单位
        QConstructionUnitEntity  q =QConstructionUnitEntity.constructionUnitEntity;

        Predicate predicate=q.isNotNull().or(q.isNull());
        predicate = (unitName == null || unitName.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.entName.like("%" + unitName + "%"));
        predicate = (uniscid == null || uniscid.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.uniscid.like("%" + uniscid + "%"));
        predicate = ExpressionUtils.and(predicate,q.delFlag.eq(Constant.NO_DELETE));
        List<ConstructionUnitEntity> list = jpaQueryFactory.selectFrom(q)
                .where(predicate)
                .fetch();
        return list;
    }*/


}
